package alkaid.oss.minio.config;

import java.rmi.NoSuchObjectException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import alkaid.oss.common.util.ErrorResponse;
import alkaid.oss.common.util.ThrowableFiltered;
import alkaid.oss.minio.util.MinioOssException;
import alkaid.oss.minio.util.NoSuchKeyException;
import lombok.extern.slf4j.Slf4j;

/**
 * 统一异常处理
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
    @ExceptionHandler({NoSuchObjectException.class, NoSuchKeyException.class})
    public ResponseEntity<?> handleNotFound(MinioOssException e) {
        log.warn("业务异常 {} {}", System.lineSeparator(), ThrowableFiltered.INSTANCE.renderLine(e));

        HttpStatus status = HttpStatus.NOT_FOUND;
        return ResponseEntity.status(status).body(ErrorResponse.of(e, status.value()));
    }

    @ExceptionHandler(MinioOssException.class)
    public ResponseEntity<?> handleBadRequest(MinioOssException e) {
        log.warn("业务异常 {} {}", System.lineSeparator(), ThrowableFiltered.INSTANCE.renderLine(e));

        HttpStatus status = HttpStatus.BAD_REQUEST;
        return ResponseEntity.status(status).body(ErrorResponse.of(e, status.value()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleInternalServerError(Exception e) {
        log.error("系统异常", e);

        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        return ResponseEntity.status(status).body(ErrorResponse.of(e, status.value()));
    }  
}
